package wangjg.mda.gen.template;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;

/**
 * 处理空白字符的指令
 * @author wangjg
 *
 */
public class TrimDirective extends Directive {

	@Override
	public String getName() {
		return "trim";
	}

	@Override
	public int getType() {
		return BLOCK;
	}

	@Override
	public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
		SimpleNode param0 = (SimpleNode) node.jjtGetChild(0);
		String mode = (String)param0.value(context);
		SimpleNode param1 = (SimpleNode) node.jjtGetChild(1);
		Integer tabNum = (Integer)param1.value(context);
		SimpleNode param2 = (SimpleNode) node.jjtGetChild(2);
		String newLine = (String)param2.value(context);
		
		Node bodyNode = node.jjtGetChild(node.jjtGetNumChildren()-1);
		StringWriter sw = new StringWriter();
		bodyNode.render(context, sw);
		String bodyStr = sw.toString().trim();

		String tbs = "";
		if(tabNum!=null){
			for(int i=0;i<tabNum;i++){
				tbs += "\t";
			}
		}
		
		if(!"eachrow".equals(mode)){
			bodyStr = tbs+bodyStr.trim();
		}else{
			StringReader sr = new StringReader(bodyStr);
			BufferedReader br = new BufferedReader(sr);
			String line = null;
			StringBuilder tmp = new StringBuilder();
			String enter = "\n";
			if("rn".equals(newLine)){
				enter = "\r\n";
			}
			while((line=br.readLine())!=null){
				line = line.trim();
				if(line.length()==0){
					continue;
				}
				tmp.append(tbs);
				tmp.append(line);
				tmp.append(enter);
			}
			bodyStr = tmp.toString();
			if(bodyStr.endsWith(enter)){
				bodyStr = bodyStr.substring(0, bodyStr.length()-enter.length());
			}
		}
		writer.write(bodyStr);
		return true;
	}
}